<template>
  <div class="app-container">
    <el-row class="test">
      <connect-chose module="fastdfs" v-model="connName" />
    </el-row>

    <el-row>
      <el-tabs active-name="preview" v-loading="uploadLoading">
        <el-tab-pane label="预览下载" name="preview">
          <el-form size="small" label-width="120px">
            <el-form-item>
              <el-button-group>
                <el-button size="small" type="primary" icon="el-icon-view" :disabled="!dfsIds"  @click="preview" title="点击切换下一张图">预览</el-button>
                <el-button size="small" icon="el-icon-download" :disabled="!dfsIds" @click="download">下载</el-button>
              </el-button-group>
            </el-form-item>

            <el-form-item label="dfsId">
              <el-input
                :disabled="!connName"
                v-model="dfsIds" size="small" clearable placeholder="填写 dfsId , 可以填写多个, 使用逗号或者换行进行分隔"
                @keyup.enter.native="preview"
                type="textarea"
                :autosize="{ minRows: 1, maxRows: 5}"
              />
            </el-form-item>
          </el-form>

          <template v-if="image">
            <el-row>
              <el-col :span="4" class="padding">
                <el-descriptions :column="1" size="small" title="文件信息" border>
                  <el-descriptions-item label="数据来源">{{fileInfo.sourceIpAddr}}</el-descriptions-item>
                  <el-descriptions-item label="文件类型">{{fileInfo.fileType === 1 ? '常规文件': fileInfo.fileType}}</el-descriptions-item>
                  <el-descriptions-item label="文件大小">{{formatSizeHuman(fileInfo.fileSize)}}</el-descriptions-item>
                  <el-descriptions-item label="创建时间">{{fileInfo.createTimestamp}}</el-descriptions-item>
                  <el-descriptions-item label="CRC32">{{fileInfo.crc32}}</el-descriptions-item>
                </el-descriptions>
              </el-col>
              <el-col :span="18">
                <el-image :src="image" style="width: 100%"  :preview-src-list="[image]" />
              </el-col>
            </el-row>

          </template>
          <template v-else>填写 dfsId 地址来预览图片</template>
        </el-tab-pane>
        <el-tab-pane name="upload" label="上传">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="#"
            :on-change="setUploadFiles"
            :multiple="true"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">别上传太大的文件, 10M 以内吧</div>
          </el-upload>

          <div v-if="uploadResult.length > 0">
            <el-alert type="success">上传结果</el-alert>

            <ul class="list-group">
              <li class="list-group-item" style="display: flex;justify-content: space-between" v-for="uploadItem in uploadResult">
                <b> {{uploadItem.key}} </b>
                <span> {{uploadItem.value}} </span>
              </li>
            </ul>
          </div>

        </el-tab-pane>
      </el-tabs>
    </el-row>
  </div>
</template>

<script>
import ConnectChose from '@/views/components/ConnectChose'

import fastdfs from '@/api/fastdfs'
import TemplateExample from '@/views/database/code/TemplateExample'

import {formatSizeHuman,formatTime,download} from '@/utils'

export default {
  name: 'fastdfs',
  components: { TemplateExample, ConnectChose},
  data(){
    return {
      connName: null,
      dfsIds: null,
      image: null,
      fileInfo: {},
      previewCount: 0,
      uploadFiles: [],
      uploadResult: [],
      uploadLoading: false
    }
  },
  created() {
    this.previewCount = 0;
  },
  methods: {
    formatSizeHuman,formatTime,
    // changeConnName(connName){
    //   this.connName = connName
    // },
    checkFileInfo(callback){
      if (!this.connName || !this.dfsIds){
        this.$message('填写文件路径信息')
        return
      }
      let dfsIdArray = this.dfsIds.split(/[\n,]/)
      let index = this.previewCount % dfsIdArray.length;
      fastdfs.fileInfo(this.connName,dfsIdArray[index]).then(res => {
        this.fileInfo = res.data

        callback(dfsIdArray[index]);
      })
    },
    preview(){
      this.checkFileInfo((dfsId) => {
        this.previewCount ++
        fastdfs.preview(this.connName,dfsId)
          .then(response => {
            return 'data:image/png;base64,' +btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
          }).then(data => {
          this.image = data;
        })
      })

    },
    download(){
      this.checkFileInfo(() => {
        fastdfs.download(this.connName,this.dfsIds)
      })
    },
    setUploadFiles(file, filelist){
      this.uploadFiles = filelist.map(file => file.raw)
    },
    submitUpload(){
      this.uploadLoading = true
      const formData = new FormData()
      for (let i = 0; i < this.uploadFiles.length; i++) {
        formData.append('files', this.uploadFiles[i], this.uploadFiles[i].name)
      }
      formData.append('connName',this.connName)
      fastdfs.uploadFiles(formData).then(res => {
        this.uploadLoading = false
        this.uploadResult = res.data
      }).catch(res => {
        this.uploadLoading = false
      })
    }
  }
}
</script>

<style scoped>
  @import "../../assets/custom-theme/bootstrap.css";
  .test{}
</style>
